﻿using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace HurricanePackage
{
    /// <summary>
    /// 可挂载的状态机基类
    /// </summary>
    public abstract class BaseFsmForMono<SID, TID> : MonoBehaviour
        where SID : Enum //状态机id
        where TID : Enum //条件id
    {
        /// <summary>
        /// 状态ID列表
        /// 需要派生类利用Inspector面板选择填充
        /// </summary>
        public abstract List<SID> StateIdList { get; }

        /// <summary>
        /// 当前状态
        /// </summary>
        public SID CurrentStateType => m_curStateId;

        //状态列表
        [NotNull] protected List<BaseState<SID, TID>> m_stateList;

        //当前状态
        [NotNull] protected BaseState<SID, TID> m_curState;

        //当前状态Id
        private SID m_curStateId;

        protected object[] handleParemeter;

        // Start is called before the first frame update
        protected virtual void Start()
        {
            m_stateList = new List<BaseState<SID, TID>>();
            //配置状态机
            _ConfigStates();
            _OnInitDone();
        }

        // Update is called once per frame
        void Update()
        {
            m_curState.Reason(handleParemeter);
            m_curState.StayState();
        }


        //配置状态机
        private void _ConfigStates()
        {
            if (StateIdList.Count == 0)
                return;
            foreach (var stateId in StateIdList)
            {
                //缓存池
                var state = _GetState(stateId);
                m_stateList.Add(state);
            }
            //绑定切换动作
            BaseState<SID, TID>.ChangeStateAct = SetState;
        }


        /// <summary>
        /// 切换状态
        /// </summary>
        public void SetState(SID _targetStateId)
        {
            //设置寻找目标状态
           var newState= m_stateList.Find(t => t.StateId.CompareTo(_targetStateId) ==0);
           if (newState != null)
           {
               //退出当前
               m_curState?.ExitState();
               //设置新状态进入
                m_curState = newState;
               m_curState.EnterState();
               m_curStateId = newState.StateId;
           }
        }


        private void OnDestroy()
        {
            //foreach (var state in m_stateList)
            //{
            //    state?.Recycle();
            //}
            //m_stateList.Clear();
            //m_stateList = null;
        }

        protected void OnApplicationQuit()
        {
            //foreach (var state in m_stateList)
            //{
            //    state?.Recycle();
            //}
            //m_stateList.Clear();
            //m_stateList = null;
        }

        protected abstract void _OnInitDone();
        /// <summary>
        /// 获取实际状态类
        /// </summary>
        protected abstract BaseState<SID, TID> _GetState(SID _stateId);

    }
}

